<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar
    class="page-nav-bar"
    title="个人信息"
    left-arrow
    @click-left="$router.back()" />
    <!-- /导航栏 -->
    <input type="file" hidden ref="file" @change="inputChange">
    <van-cell @click="$refs.file.click()" title="头像" is-link>
      <van-image
        class="avatar"
        fit="cover"
        round
        :src="users.photo"
      />
    </van-cell>
    <van-cell title="昵称" @click="isShowEditNickname = true" :value="users.name" is-link />
    <van-cell title="性别" @click="isShowEditGender = true" :value="users.gender ? '女' : '男'" is-link />
    <van-cell title="生日" @click="isShowEditBirthday = true" :value="users.birthday" is-link />

    <!-- 编辑昵称弹层 -->
    <van-popup v-model="isShowEditNickname" position="bottom" :style="{ height: '100%' }">
      <EditNickname v-if="isShowEditNickname" v-model="users.name" @click-left="isShowEditNickname = false" />
      <!-- v-model -->
      <!-- :value="users.name" -->
      <!-- @input="users.name = $event" -->
    </van-popup>

    <!-- 编辑性别 -->
    <van-popup v-model="isShowEditGender" position="bottom">
      <EditGender v-if="isShowEditGender" v-model="users.gender" @cancel="isShowEditGender = false" />
    </van-popup>

    <!-- 编辑生日 -->
    <van-popup v-model="isShowEditBirthday" position="bottom">
      <EditBirthday v-if="isShowEditBirthday" v-model="users.birthday" @cancel="isShowEditBirthday = false" />
    </van-popup>

    <!-- 编辑头像 -->
    <van-popup style="height: 100%" v-model="isShowEditAvatar" position="bottom">
      <EditAvatar @on-success="users.photo = $event" @cancel="isShowEditAvatar = false" :img="imgSrc"/>
    </van-popup>
  </div>
</template>

<script>
import { getUserProfile } from '@/api/user.js'
import EditNickname from './components/edit-nickname'
import EditGender from './components/edit-gender'
import EditBirthday from './components/edit-birthday'
import EditAvatar from './components/edit-avatar'
export default {
  data () {
    return {
      users: {},
      isShowEditNickname: false,
      isShowEditGender: false,
      isShowEditBirthday: false,
      isShowEditAvatar: false,
      imgSrc: ''
    }
  },

  components: {
    EditNickname,
    EditGender,
    EditBirthday,
    EditAvatar
  },

  created () {
    this.loadUserProfile()
  },

  methods: {
    async loadUserProfile () {
      const res = await getUserProfile()
      this.users = res
    },
    inputChange (e) {
      // value 发生变化 选择图片了
      this.isShowEditAvatar = true
      const file = e.target.files[0]
      // 将文件对象转成url
      this.imgSrc = URL.createObjectURL(file)
      e.target.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
}
</style>
